import {
  Column,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from "typeorm";
import { Systems } from "./Systems";
import { Users } from "./Users";

@Index("fk_organizations_parent_id", ["parentId"], {})
@Index("fk_organizations_systems_id", ["systemId"], {})
@Entity("organizations", { schema: "nest-demo" })
export class Organizations {
  @PrimaryGeneratedColumn({ type: "int", name: "id", unsigned: true })
  id: number;

  @Column("int", { name: "system_id", comment: "所属系统ID", unsigned: true })
  systemId: number;

  @Column("int", {
    name: "parent_id",
    nullable: true,
    comment: "父级组织ID",
    unsigned: true,
  })
  parentId: number | null;

  @Column("varchar", { name: "name", comment: "组织名称", length: 100 })
  name: string;

  @Column("varchar", { name: "code", comment: "组织代码", length: 50 })
  code: string;

  @Column("enum", {
    name: "type",
    nullable: true,
    comment: "组织类型",
    enum: ["department", "team", "company"],
    default: 'department',
  })
  type: "department" | "team" | "company" | null;

  @Column("varchar", {
    name: "path",
    nullable: true,
    comment: "组织路径(用于快速查询)",
    length: 500,
  })
  path: string | null;

  @Column("int", {
    name: "sort",
    nullable: true,
    comment: "排序",
    default: () => "'0'",
  })
  sort: number | null;

  @Column("tinyint", {
    name: "status",
    nullable: true,
    comment: "状态: 0-禁用, 1-启用",
    default: () => "'1'",
  })
  status: number | null;

  @Column("timestamp", {
    name: "created_at",
    nullable: true,
    default: () => "CURRENT_TIMESTAMP",
  })
  createdAt: Date | null;

  @Column("timestamp", {
    name: "updated_at",
    nullable: true,
    default: () => "CURRENT_TIMESTAMP",
  })
  updatedAt: Date | null;

  @ManyToOne(
    () => Organizations,
    (organizations) => organizations.organizations,
    { onDelete: "RESTRICT", onUpdate: "RESTRICT" }
  )
  @JoinColumn([{ name: "parent_id", referencedColumnName: "id" }])
  parent: Organizations;

  @OneToMany(() => Organizations, (organizations) => organizations.parent)
  organizations: Organizations[];

  @ManyToOne(() => Systems, (systems) => systems.organizations, {
    onDelete: "RESTRICT",
    onUpdate: "RESTRICT",
  })
  @JoinColumn([{ name: "system_id", referencedColumnName: "id" }])
  system: Systems;

  @OneToMany(() => Users, (users) => users.organization)
  users: Users[];
}
